
public class MatBasica implements Expressao {

	private Expressao expr1;
	private Expressao expr2;
	private String acao;
	private Integer regFinal;

	public MatBasica(Expressao expr1, Expressao expr2, String acao) {
		this.expr1 = expr1;
		this.expr2 = expr2;
		this.acao = decodeAcao(acao);
	}

	private String decodeAcao(String acao) {
		if (acao.equals("+")) return "SUM"; 
		if (acao.equals("-")) return "SUB";
		if (acao.equals("*")) return "MUL";
		if (acao.equals("/")) return "DIV";
		
		return "";
	}
	
	@Override
	public String getCode() {
		StringBuffer sb = new StringBuffer();
		Integer regNumber = null;
		Integer regNumber2 = null;
		
		String s1 = expr1.getCode();
		
		if (expr1.possuiRegistradorFinal()) {
			sb.append(s1);
		} else {
			regNumber = ParserUtils.novoRegistrador();
			sb.append("LD R" + regNumber + ", " + s1);
		}
		sb.append(System.lineSeparator());
		
		String s2 = expr2.getCode();
		
		if (expr2.possuiRegistradorFinal()) {
			sb.append(s2);
		} else {
			regNumber2 = ParserUtils.novoRegistrador();
			sb.append("LD R" + regNumber2 + ", " + s2);
		}
		sb.append(System.lineSeparator());
		
		String r1 = expr1.possuiRegistradorFinal() ? expr1.registradorFinal()+"" : regNumber + "";
		String r2 = expr2.possuiRegistradorFinal() ? expr2.registradorFinal()+"" : regNumber2 + "";
		
		regFinal = ParserUtils.novoRegistrador();
		sb.append(acao + " R" + regFinal + ", R"+ r1 + ", R" + r2);
		
		ParserUtils.liberaRegistradores(regFinal);
		if (regNumber != null) ParserUtils.liberaRegistradores(regNumber);
		if (regNumber2 != null) ParserUtils.liberaRegistradores(regNumber2);
		return sb.toString();
	}

	@Override
	public Integer registradorFinal() {
		return regFinal;
	}

	@Override
	public boolean possuiRegistradorFinal() {
		return true;
	}

}
